/**
 * Ollama Llava3多模态AI助手
 * 支持图像上传和分析，以及文本+图像的混合对话
 */

'use client'

import React, { useState, useRef, useCallback, useEffect } from 'react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { 
  Bot, 
  Send, 
  X, 
  Camera, 
  Upload,
  Image as ImageIcon,
  Eye,
  Trash2,
  Download,
  Loader2,
  AlertCircle,
  FileText,
  Zap
} from 'lucide-react'
import { toast } from 'sonner'
import { realAIService } from '@/lib/realAIService'

interface OllamaLlavaAssistantProps {
  className?: string
  userId?: string
  onAnalysisComplete?: (result: any) => void
  initialMode?: 'analysis' | 'chat'
}

interface AnalysisMessage {
  id: string
  type: 'user' | 'assistant' | 'image'
  content: string
  imageData?: string
  timestamp: Date
  metadata?: {
    analysisType?: string
    includeRecommendations?: boolean
    processingTime?: number
    model?: string
    provider?: string
  }
}

export const OllamaLlavaAssistant: React.FC<OllamaLlavaAssistantProps> = ({
  className = '',
  userId = 'default',
  onAnalysisComplete,
  initialMode = 'analysis'
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const [activeMode, setActiveMode] = useState<'analysis' | 'chat'>(initialMode)
  const [messages, setMessages] = useState<AnalysisMessage[]>([])
  const [inputValue, setInputValue] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [selectedImage, setSelectedImage] = useState<string | null>(null)
  const [analysisType, setAnalysisType] = useState<'general' | 'xray' | 'ct' | 'mri' | 'ultrasound'>('general')
  const [includeRecommendations, setIncludeRecommendations] = useState(false)
  const [dragOver, setDragOver] = useState(false)
  
  const fileInputRef = useRef<HTMLInputElement>(null)
  const messagesEndRef = useRef<HTMLDivElement>(null)

  // 滚动到底部
  const scrollToBottom = useCallback(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [])

  useEffect(() => {
    scrollToBottom()
  }, [messages, scrollToBottom])

  // 初始化欢迎消息
  useEffect(() => {
    if (isOpen && messages.length === 0) {
      const welcomeMessage: AnalysisMessage = {
        id: `welcome_${Date.now()}`,
        type: 'assistant',
        content: activeMode === 'analysis' 
          ? '🖼️ 欢迎使用Llava3图像分析功能！\n\n我可以帮您:\n• 📊 分析医疗图像(X光、CT、MRI、超声)\n• 🔍 识别图像中的对象和内容\n• 💡 提供专业的医疗建议\n• 📋 生成详细的分析报告\n\n请上传一张图片开始分析，或切换到对话模式进行多模态聊天。'
          : '💬 欢迎使用Llava3多模态对话！\n\n我可以:\n• 🖼️ 同时理解文字和图片\n• 🩺 提供医疗相关咨询\n• 📝 生成详细的分析报告\n• 🤖 进行智能对话\n\n您可以发送文字消息，或者上传图片进行多模态交流。',
        timestamp: new Date()
      }
      setMessages([welcomeMessage])
    }
  }, [isOpen, activeMode, messages.length])

  // 处理文件选择
  const handleFileSelect = useCallback((file: File) => {
    if (!file.type.startsWith('image/')) {
      toast.error('请选择图片文件')
      return
    }

    if (file.size > 10 * 1024 * 1024) { // 10MB limit
      toast.error('图片大小不能超过10MB')
      return
    }

    const reader = new FileReader()
    reader.onload = (e) => {
      const base64 = e.target?.result as string
      setSelectedImage(base64)
      
      if (activeMode === 'analysis') {
        // 在分析模式下，自动添加图片消息
        const imageMessage: AnalysisMessage = {
          id: `image_${Date.now()}`,
          type: 'image',
          content: `已上传图片: ${file.name}`,
          imageData: base64,
          timestamp: new Date()
        }
        setMessages(prev => [...prev, imageMessage])
      }
    }
    reader.readAsDataURL(file)
  }, [activeMode])

  // 拖拽处理
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(true)
  }, [])

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)
  }, [])

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)
    
    const files = Array.from(e.dataTransfer.files)
    if (files.length > 0) {
      handleFileSelect(files[0])
    }
  }, [handleFileSelect])

  // 分析图像
  const analyzeImage = async (imageData: string, prompt?: string) => {
    setIsLoading(true)
    
    try {
      const response = activeMode === 'analysis' && analysisType !== 'general'
        ? await realAIService.analyzeMedicalImage(
            imageData, 
            analysisType, 
            { 
              sessionId: userId,
              includeRecommendations 
            }
          )
        : await realAIService.analyzeImage(
            imageData, 
            prompt || '请分析这张图片，描述你看到的内容并提供专业建议。',
            {
              sessionId: userId,
              temperature: 0.7,
              maxTokens: 4000
            }
          )

      const aiMessage: AnalysisMessage = {
        id: response.id,
        type: 'assistant',
        content: response.content,
        timestamp: new Date(),
        metadata: {
          analysisType,
          includeRecommendations,
          processingTime: response.metadata?.processingTime,
          model: response.model,
          provider: response.provider
        }
      }

      setMessages(prev => [...prev, aiMessage])
      
      if (onAnalysisComplete) {
        onAnalysisComplete({
          content: response.content,
          imageData,
          analysisType,
          metadata: response.metadata
        })
      }

      toast.success('图像分析完成！')
    } catch (error) {
      console.error('图像分析失败:', error)
      const errorMessage: AnalysisMessage = {
        id: `error_${Date.now()}`,
        type: 'assistant',
        content: `❌ 图像分析失败: ${error.message}\n\n请检查：\n• Ollama服务是否正常运行\n• llava3模型是否已下载\n• 网络连接是否正常`,
        timestamp: new Date()
      }
      setMessages(prev => [...prev, errorMessage])
      toast.error('图像分析失败，请重试')
    } finally {
      setIsLoading(false)
    }
  }

  // 发送消息
  const handleSendMessage = async () => {
    if (activeMode === 'analysis') {
      // 分析模式：需要有图片才能分析
      if (!selectedImage) {
        toast.error('请先上传图片')
        return
      }
      await analyzeImage(selectedImage, inputValue || undefined)
    } else {
      // 对话模式：支持纯文本或文本+图片
      if (!inputValue.trim() && !selectedImage) {
        toast.error('请输入消息或上传图片')
        return
      }

      const userMessage: AnalysisMessage = {
        id: `user_${Date.now()}`,
        type: 'user',
        content: inputValue || (selectedImage ? '请分析这张图片' : ''),
        imageData: selectedImage || undefined,
        timestamp: new Date()
      }

      setMessages(prev => [...prev, userMessage])
      setIsLoading(true)

      try {
        // 构建消息内容
        const messageContent = selectedImage ? [
          {
            type: 'text' as const,
            text: inputValue || '请分析这张图片，并提供专业的医疗建议。'
          },
          {
            type: 'image_url' as const,
            image_url: {
              url: selectedImage,
              detail: 'high' as const
            }
          }
        ] : inputValue

        const messages = [{
          role: 'user' as const,
          content: messageContent
        }]

        const response = await realAIService.chat(messages, {
          provider: 'ollama',
          sessionId: userId,
          temperature: 0.7,
          maxTokens: 4000
        })

        const aiMessage: AnalysisMessage = {
          id: response.id,
          type: 'assistant',
          content: response.content,
          timestamp: new Date(),
          metadata: {
            processingTime: response.metadata?.processingTime,
            model: response.model,
            provider: response.provider
          }
        }

        setMessages(prev => [...prev, aiMessage])
        toast.success('对话完成！')
      } catch (error) {
        console.error('对话失败:', error)
        const errorMessage: AnalysisMessage = {
          id: `error_${Date.now()}`,
          type: 'assistant',
          content: `❌ 对话失败: ${error.message}`,
          timestamp: new Date()
        }
        setMessages(prev => [...prev, errorMessage])
        toast.error('对话失败，请重试')
      } finally {
        setIsLoading(false)
      }
    }

    setInputValue('')
    setSelectedImage(null)
  }

  // 清除选中的图片
  const clearSelectedImage = () => {
    setSelectedImage(null)
  }

  // 清空对话
  const clearMessages = () => {
    setMessages([])
    setSelectedImage(null)
    setInputValue('')
  }

  if (!isOpen) {
    return (
      <Button
        onClick={() => setIsOpen(true)}
        className={`fixed bottom-4 right-4 z-50 bg-purple-600 hover:bg-purple-700 text-white shadow-lg ${className}`}
        size="lg"
      >
        <Bot className="w-5 h-5 mr-2" />
        Llava3 AI
      </Button>
    )
  }

  return (
    <Card className={`fixed bottom-4 right-4 z-50 w-96 h-[600px] shadow-2xl ${className}`}>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <div className="flex items-center space-x-2">
          <div className="relative">
            <Bot className="w-5 h-5 text-purple-600" />
            <div className="absolute -top-1 -right-1 w-3 h-3 bg-green-500 rounded-full border-2 border-white"></div>
          </div>
          <div>
            <CardTitle className="text-sm font-medium">Llava3 AI助手</CardTitle>
            <p className="text-xs text-gray-500">多模态图像分析</p>
          </div>
        </div>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setIsOpen(false)}
        >
          <X className="w-4 h-4" />
        </Button>
      </CardHeader>

      <CardContent className="flex flex-col h-full p-3">
        {/* 模式切换 */}
        <Tabs value={activeMode} onValueChange={(v) => setActiveMode(v as any)} className="w-full mb-3">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="analysis" className="flex items-center gap-1">
              <Eye className="w-3 h-3" />
              分析
            </TabsTrigger>
            <TabsTrigger value="chat" className="flex items-center gap-1">
              <Bot className="w-3 h-3" />
              对话
            </TabsTrigger>
          </TabsList>

          <TabsContent value="analysis" className="space-y-2 mt-2">
            <div className="grid grid-cols-2 gap-2 text-xs">
              <div>
                <Label htmlFor="analysis-type">分析类型</Label>
                <Select value={analysisType} onValueChange={(v) => setAnalysisType(v as any)}>
                  <SelectTrigger className="h-8">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="general">通用分析</SelectItem>
                    <SelectItem value="xray">X光片</SelectItem>
                    <SelectItem value="ct">CT扫描</SelectItem>
                    <SelectItem value="mri">MRI图像</SelectItem>
                    <SelectItem value="ultrasound">超声图像</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center space-x-2 pt-6">
                <Switch
                  id="recommendations"
                  checked={includeRecommendations}
                  onCheckedChange={setIncludeRecommendations}
                />
                <Label htmlFor="recommendations" className="text-xs">建议</Label>
              </div>
            </div>
          </TabsContent>

          <TabsContent value="chat" className="mt-2">
            <p className="text-xs text-gray-600">多模态对话模式，支持文本+图像交互</p>
          </TabsContent>
        </Tabs>

        {/* 消息列表 */}
        <div className="flex-1 overflow-y-auto space-y-2 mb-3 min-h-0">
          {messages.map((message) => (
            <div
              key={message.id}
              className={`flex ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}
            >
              <div
                className={`max-w-[80%] rounded-lg p-2 text-sm ${
                  message.type === 'user'
                    ? 'bg-purple-600 text-white'
                    : message.type === 'image'
                    ? 'bg-blue-100 border border-blue-200'
                    : 'bg-gray-100 text-gray-800'
                }`}
              >
                {message.imageData && (
                  <div className="mb-2">
                    <img 
                      src={message.imageData} 
                      alt="分析图片" 
                      className="max-w-full h-auto rounded border"
                      style={{ maxHeight: '150px' }}
                    />
                  </div>
                )}
                <div className="whitespace-pre-wrap">{message.content}</div>
                {message.metadata && (
                  <div className="mt-1 text-xs opacity-70">
                    <div>模型: {message.metadata.model}</div>
                    {message.metadata.processingTime && (
                      <div>耗时: {message.metadata.processingTime}ms</div>
                    )}
                  </div>
                )}
              </div>
            </div>
          ))}
          {isLoading && (
            <div className="flex justify-start">
              <div className="bg-gray-100 rounded-lg p-2 text-sm flex items-center space-x-2">
                <Loader2 className="w-4 h-4 animate-spin" />
                <span>正在分析中...</span>
              </div>
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>

        {/* 图片预览和上传区域 */}
        {selectedImage && (
          <div className="mb-3 p-2 border rounded-lg bg-gray-50">
            <div className="flex items-center justify-between mb-2">
              <span className="text-xs text-gray-600">已选择图片:</span>
              <Button
                variant="ghost"
                size="sm"
                onClick={clearSelectedImage}
                className="h-6 px-2"
              >
                <Trash2 className="w-3 h-3" />
              </Button>
            </div>
            <img 
              src={selectedImage} 
              alt="选择的图片" 
              className="w-full h-20 object-cover rounded border"
            />
          </div>
        )}

        {/* 拖拽上传区域 */}
        <div
          className={`border-2 border-dashed rounded-lg p-3 text-center transition-colors ${
            dragOver ? 'border-purple-500 bg-purple-50' : 'border-gray-300'
          }`}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
        >
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            onChange={(e) => {
              const file = e.target.files?.[0]
              if (file) handleFileSelect(file)
            }}
            className="hidden"
          />
          <div className="flex flex-col items-center space-y-2">
            <ImageIcon className="w-6 h-6 text-gray-400" />
            <div className="text-xs text-gray-600">
              拖拽图片到这里或
              <button
                onClick={() => fileInputRef.current?.click()}
                className="text-purple-600 hover:underline ml-1"
              >
                点击选择
              </button>
            </div>
          </div>
        </div>

        {/* 输入区域 */}
        <div className="flex space-x-2 mt-3">
          <Input
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder={
              activeMode === 'analysis' 
                ? '输入分析要求（可选）...' 
                : '输入消息...'
            }
            onKeyPress={(e) => {
              if (e.key === 'Enter') {
                handleSendMessage()
              }
            }}
            className="flex-1 text-sm"
          />
          <Button
            onClick={handleSendMessage}
            disabled={isLoading || (activeMode === 'analysis' && !selectedImage)}
            size="sm"
            className="bg-purple-600 hover:bg-purple-700"
          >
            {isLoading ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Send className="w-4 h-4" />
            )}
          </Button>
        </div>

        {/* 底部操作 */}
        <div className="flex justify-between items-center mt-2 pt-2 border-t">
          <Badge variant="secondary" className="text-xs">
            <Zap className="w-3 h-3 mr-1" />
            Llava3
          </Badge>
          <Button
            variant="ghost"
            size="sm"
            onClick={clearMessages}
            className="text-xs h-6 px-2"
          >
            清空
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}

export default OllamaLlavaAssistant